package com.lm.service.impl;

import com.lm.dao.KwChannelDao;
import com.lm.dao.LmUserBaseDao;
import com.lm.dao.LmUserDao;
import com.lm.dao.LmUserLoginDao;
import com.lm.model.KwChannel;
import com.lm.model.LmUser;
import com.lm.model.LmUserBase;
import com.lm.model.LmUserLogin;
import com.lm.service.KwChannelService;
import com.lm.service.LmUserLoginService;
import com.meirengu.common.PasswordEncryption;
import com.meirengu.service.impl.BaseServiceImpl;
import com.meirengu.utils.NumberUtil;
import com.meirengu.utils.RandomUtil;
import com.meirengu.utils.StringUtil;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * LmUserLogin服务实现层
 *
 * @author Mao
 * @create Sat May 05 16:28:14 CST 2018
 */
@Service
public class LmUserLoginServiceImpl extends BaseServiceImpl<LmUserLogin> implements LmUserLoginService {

    private static final Logger logger = LoggerFactory.getLogger(LmUserLoginServiceImpl.class);

    @Autowired
    LmUserLoginDao lmUserLoginDao;
    @Autowired
    KwChannelDao kwChannelDao;
    @Autowired
    LmUserDao lmUserDao;
    @Autowired
    LmUserBaseDao lmUserBaseDao;
    @Autowired
    KwChannelService kwChannelService;

    public LmUserLogin detailByPhone(String phone) throws Exception {
        return lmUserLoginDao.detailByPhone(phone);
    }

    public LmUserLogin createUser(String phone, String password, String channelCode, String icode, Integer paltform, String platformCode, String ip, String userAgent) throws Exception {
        Date now = new Date();
        LmUser lmUser = new LmUser();
        lmUser.setCreateDate(now);
        lmUser.setPhone(phone);
        lmUser.setIp(ip);
        lmUser.setSubmitStage(1);
        lmUser.setUserAgent(userAgent);
        lmUserDao.insert(lmUser);

        LmUserBase lmUserBase = new LmUserBase();
        lmUserBase.setCreateDate(now);
        lmUserBase.setPhone(phone);
        if (!StringUtil.isEmpty(platformCode)) {
            int platformId = getPlatfrom(platformCode);
            lmUserBase.setRegisterFrom(platformId);
        }
        //查询渠道信息
        if (StringUtils.isNotBlank(channelCode)) {
            lmUserBase.setChannelCode(channelCode);
            KwChannel channel = kwChannelDao.getByCode(channelCode);
            if (StringUtils.isEmpty(icode)) {
                if (channel != null) {
                    //lmUserBase.setChannelId(channel.getId());
                    lmUserBase.setChannelName(channel.getChannelName());
                }
            }
        }
        lmUserBase.setUserId(lmUser.getId());
        lmUserBaseDao.insert(lmUserBase);

        LmUserLogin lmUserLogin = new LmUserLogin();
        lmUserLogin.setCreateDate(now);
        lmUserLogin.setPhone(phone);
        if (!StringUtil.isEmpty(platformCode)) {
            int platformId = getPlatfrom(platformCode);
            lmUserLogin.setRegisterFrom(platformId);
        }
        lmUserLogin.setNickName(getNickName());
        //初次设置用户为普通用户
        lmUserLogin.setUserType(1);
        if (!StringUtils.isEmpty(icode)) {
            LmUserLogin invitationUser = lmUserLoginDao.detailByIcode(icode);
            if (invitationUser != null) {
                lmUserLogin.setInvitationUserId(invitationUser.getId());
            }
        }
        try {
            lmUserLogin.setPassword(PasswordEncryption.createHash(password));
        } catch (Exception e) {
            logger.error("加密密码失败！");
        }
        try {
            boolean flag = true;
            String invitationCode = "";
            while (flag) {
                //没有注册码则生成
                invitationCode = RandomUtil.generateInvitationCode();
                //判断是否重复
                flag = lmUserLoginDao.detailByIcode(invitationCode) != null ? true : false;
            }
            lmUserLogin.setInvitationCode(invitationCode);
        } catch (Exception e) {
            logger.error("创建邀请码失败！");
        }
        lmUserLogin.setUserId(lmUser.getId());
        lmUserLogin.setBaseId(lmUserBase.getId());
        lmUserLoginDao.insert(lmUserLogin);

        return lmUserLogin;
    }

    public LmUserLogin detailByIcode(String icode) throws Exception {
        return lmUserLoginDao.detailByIcode(icode);
    }

    //更新用户的登录信息
    public int updateLogin(LmUserLogin lmUserLogin, Integer paltform, String ip) throws Exception {
        if (!StringUtil.isEmpty(lmUserLogin.getLoginIp())) {
            lmUserLogin.setLastLoginIp(lmUserLogin.getLoginIp());
        }
        lmUserLogin.setLoginIp(ip);
        if (lmUserLogin.getLoginTime() != null) {
            logger.debug("LastLoginTime:" + lmUserLogin.getLoginTime());
            lmUserLogin.setLastLoginTime(lmUserLogin.getLoginTime());
        }
        lmUserLogin.setLoginTime(new Date());
        lmUserLogin.setLoginFrom(paltform);
        if (NumberUtil.isNullOrZero(lmUserLogin.getLoginNum())) {
            lmUserLogin.setLoginNum(1);
        } else {
            lmUserLogin.setLoginNum(lmUserLogin.getLoginNum() + 1);
        }
        return lmUserLoginDao.update(lmUserLogin);
    }

    public String getNickName() {
        int randNum = RandomUtils.nextInt(100000, 999999);
        return "lm" + randNum;
    }

    /**
     * 注册平台
     *
     * @param platfromCode
     * @return
     */
    private int getPlatfrom(String platfromCode) {
        if (platfromCode == null) return 2;
        if (platfromCode.equals("h5") || platfromCode.equals("H5")) {
            return 2;
        }
        if (platfromCode.equals("apple")) {
            return 1;
        }
        return 0;
    }
}
